<template>
  <div>
    <!-- 渲染角色列表 -->
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="assignRoleSubmit">确定</el-button>
        <el-button size="small" @click="cancleDialog">取消</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getRolesAPI } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoleAPI } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      roleIds: [], // 已选角色列表
      roleList: [] // 所有角色列表
    }
  },
  created() {
    this.getRolesList()
    this.getUserDetailById()
  },
  methods: {
    // 点击确定，分配角色
    async assignRoleSubmit() {
      const res = await assignRoleAPI({ id: this.roleId, roleIds: this.roleIds })
      console.log(res)
      this.$message.success(res.message)
      this.$emit('closeEvent')
    },
    // 获取员工详情
    async getUserDetailById() {
      const res = await getUserDetailById(this.roleId)
      console.log(res)
      // 如果没有角色，后端返回null，需要先进行判断
      // this.roleIds = res.data.roleIds === null ? [] : res.data.roles
      this.roleIds = res.data.roleIds
    },
    // 获取所有角色列表
    async getRolesList() {
      const res = await getRolesAPI()
      console.log(res)
      this.roleList = res.data.rows
    },
    cancleDialog() {
      this.$emit('closeEvent')
    }
  }

}
</script>

<style scoped>
.footer{
    margin-top: 20px;
}
</style>
